package 力扣;

import java.util.*;

/**
 * @author yyq
 * @create 2022-04-04 20:27
 */
public class leetcode347 {
    public int[] topKFrequent(int[] nums, int k) {
        int[] ints=new int[k];
        HashMap<Integer,Integer> hashMap=new HashMap<>();
        for (int num : nums) {
            if(hashMap.containsKey(num)){
                hashMap.put(num,hashMap.get(num) + 1);
            }else {
                hashMap.put(num,1);
            }
        }
        //////借助list实现hashMap排序//////

        //注意 ArrayList<>() 括号里要传入map.entrySet()
        List<Map.Entry<Integer, Integer>> list = new ArrayList(hashMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>()
        {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2)
            {
                //按照value值，重小到大排序
    //             return o1.getValue() - o2.getValue();

                //按照value值，从大到小排序
                return o2.getValue() - o1.getValue();

                //按照value值，用compareTo()方法默认是从小到大排序
//                return o1.getValue().compareTo(o2.getValue());
            }
        });
        int c=0;
        for (Map.Entry<Integer, Integer> entry : list) {
            ints[c] = entry.getKey();
            c++;
            if(c==k){
                break;
            }
        }
        return ints;
    }
}
